//
//  HKNoticeViewController.m
//  HKTimeKitApp
//
//  Created by huzhaoke1 on 2023/5/8.
//

#import "HKNoticeViewController.h"
#import <Masonry/Masonry.h>
#import "HKTableAdapter.h"
#import "HKHeaderCellViewModel.h"
#import "HKHeaderCellTableViewCell.h"
#import "HKCommonDefine.h"
#import "HKUser.h"
#import "HKUserInfoViewController.h"
#import "HKProfileHeaderView.h"
#import "UIView+properties.h"
#import "HKProfileListCellModel.h"
#import "HTTPURL.h"
#import "HKRequestDefine.h"
#import "HKLoadingView.h"
#import "HKNoticeModel.h"
#import "UIView+HKSafeArea.h"
#import "HKNoticeListCellModel.h"
#import <MJRefresh/UIScrollView+MJRefresh.h>
#import "HKToastView.h"
#import "HKWebViewController.h"
#import "HKRequestDefine.h"
#import "AppDelegate.h"
#import "HKNoticeCell.h"
#import "HKShareWebViewControllerManager.h"

@interface HKNoticeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *list;
 
@end

@implementation HKNoticeViewController
 
 

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0xf7f7f7);
    [self.view addSubview:self.tableView];
    self.list = [@[]mutableCopy];

    [self.userDefinedNaviBar updateHiddenBackButton:YES];
    [self.userDefinedNaviBar updateGradienColorFromColor:UIColorFromRGB(0x448ff) toColor:UIColorFromRGB(0x8183FF)];
    [self.userDefinedNaviBar updateTitle:@"消息"];
    [self.userDefinedNaviBar updateTitleColor:[UIColor whiteColor]];
    WS
    CGFloat top = self.userDefinedNaviBar.height;
    CGFloat bottom = [HKKeyWindow ks_safeAreaInsets].bottom + 44;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        SS
        make.top.mas_equalTo(top);
        make.bottom.mas_equalTo(-bottom);
        make.width.mas_equalTo(self.view);
    }];
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        SS
        [self requestData];
        
    }];
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
    [self.tableView registerClass:[HKNoticeCell class] forCellReuseIdentifier:NSStringFromClass([HKNoticeCell class])];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestData) name:Notification_Name_MessageRefresh object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled =NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled =YES;
    }
}

- (void)requestData {
    NSString *url = HKNoticeUrl;
    WS
    [HTTPURL getjsonRequest:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        SS
        NSDictionary *response = KSSAFE_CAST(responseObject, NSDictionary);
        NSDictionary *data = response[@"data"];
        [self.tableView.mj_header endRefreshing];
        if (data && [data isKindOfClass:NSArray.class]) {
            NSArray<HKNoticeModel *> *noticeModels = [HKNoticeModel mj_objectArrayWithKeyValuesArray:response[@"data"]];
            __block BOOL isReadMessage = YES;
            [noticeModels enumerateObjectsUsingBlock:^(HKNoticeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (!obj.isRead){
                    isReadMessage = NO;
                }
            }];
            if (!isReadMessage){
                [[AppDelegate appDelegate].mainTabBarViewController showMessageTabbarItemBadge];
            }else{
                [[AppDelegate appDelegate].mainTabBarViewController clearMessageTabbarItemBadge];
            }
            [self setupCellModelsWithContents:noticeModels];
        } else {
            [[HKToastView sharedToastView] showToast:@"数据为空"];
        }
    } filure:^(NSURLSessionDataTask *task, NSError *error) {
        SS
        [[HKToastView sharedToastView] showToast:error.domain?:@"网络请求失败"];
        [self.tableView.mj_header endRefreshing];
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return self.list.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HKNoticeModel *model = self.list[indexPath.row];
    return [HKNoticeCell cellHeightWithContent:model];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HKNoticeCell *cell = (HKNoticeCell *)[tableView dequeueReusableCellWithIdentifier:@"HKNoticeCell"];
    HKNoticeModel *model = self.list[indexPath.row];
    [cell updateContent:model];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HKNoticeModel *model = self.list[indexPath.row];
    [self didSelectNoticeModel:model];
}


- (void)didSelectNoticeModel:(HKNoticeModel *)model {
    [self requestHasReadWith:model];
    NSString *url = model.currentUrl;
    if (url.length == 0) return;
    HKWebViewController *webViewController = [HKWebViewController new];
    HKWebViewContainer *webViewContainer;
    if (![[HKShareWebViewControllerManager sharedInstance] webViewContainerWithUrl:url]) {
        webViewContainer = [[HKWebViewContainer alloc] init];
    } else {
        webViewContainer = [[HKShareWebViewControllerManager sharedInstance] webViewContainerWithUrl:url];
    }
    webViewController.webViewContainer = webViewContainer;
//    [webViewController loadingRequestWithUrl:@"https://app.talkingcake.com"];
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)requestHasReadWith:(HKNoticeModel *)model {
    NSString *url = [NSString stringWithFormat:@"%@%@", HKHasReadUrl, @(model.modelId)];
    [HTTPURL getjsonRequest:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Name_MessageRefresh object:nil userInfo:nil];
    } filure:^(NSURLSessionDataTask *task, NSError *error) {
    }];
}

- (void)setupCellModelsWithContents:(NSArray<HKNoticeModel *> *)notices {
    [self.list removeAllObjects];
    [self.list addObjectsFromArray:notices];
    [self.tableView reloadData];
}
#pragma mark - getter and setter
 
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView= [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UIColorFromRGB(0xf7f7f7);
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

 
@end
